/**
 * RuleItem
 * @authors 杨兴洲（of2502）
 * @date    2017/5/25 0025 11:15
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import React, { Component } from 'react';
import { Map, List } from "immutable";
import { transformURL } from 'util/image';
import { Popover, Form, Input, Button, message, Modal, Radio } from 'antd';
import MassInput from 'uikit/mass-input';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const getReplyItem = (data) => {
    if (data.type === "text") {
        data.content = data.content || '';
        let array = data.content.split('__');
        if (['page', 'goods', 'custom'].includes(array[0])) {
            return array[1]
        } else {
            return data.content;
        }
    }
    if (data.type === "image") {
        return <img src={transformURL(data.url)} alt="content" />;
    }
    if (data.type === "mpnews") {
        return data.title;
    }
    if (data.type === "news") {
        return data.title;
    }
};
const mediaTypes = {
    text: "文本",
    image: "图片",
    mpnews: "图文",
    news: "高级图文",
    video: "视频",
    voice: "语音",
    link: "链接"
};
export default class KwRuleItem extends Component {

    static defaultProps = {
        rule: {
            ruleID: "",
            rule_name: "",
            reply_mode: "",
            reply_list_info: [],
            keyword_list_info: []
        }
    };

    constructor(props) {
        super(props);
        this.state = {
            title: props.rule.rule_name,
            titlePopVisible: false,
            keywordBtnVisible: false,
            keywordModalVisible: false,
            keywordIndex: -1,
            tempKwContent: "",
            tempKwMatchMode: "",
            tempKwType: "text",
            replyModePopVisible: false,
            replyModalVisible: false,
            // 回复
            mediaModalVisible: false,
            tempReply: {},
            replyIndex: -1,
            tempReplyModalData: {
                type: "text",
                data: null
            },// 素材选择框的初始化
        };
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ title: nextProps.rule.rule_name });
    }

    render() {
        const { rule_name, reply_mode, reply_list_info = [], keyword_list_info = [], ruleID } = this.props.rule;
        const { tempReply, tempReplyModalData, mediaModalVisible, replyIndex } = this.state;
        const replyModeTypes = { reply_all: "全部回复", random_one: "随机回复" };
        const keywordTypes = { contain: "模糊", equal: "全匹配" };
        const content = (
            <Form inline>
                <FormItem>
                    <Input size="small" value={this.state.title}
                        onChange={e => this.setState({ title: e.target.value })} />
                </FormItem>
                <FormItem>
                    <Button size="small" type="primary" onClick={this.updateTitle}>确认</Button>
                </FormItem>
                <FormItem>
                    <Button size="small" onClick={this.hideTitleEditPopover}>取消</Button>
                </FormItem>
            </Form>);

        const replyModeContent = (
            <Form inline>
                <FormItem>
                    <RadioGroup onChange={e => (this.setState({ tempReplyMode: e.target.value }))}
                        value={this.state.tempReplyMode}>
                        <Radio value="reply_all">全部回复</Radio>
                        <Radio value="random_one">随机回复</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem>
                    <Button size="small" type="primary" onClick={this.updateReplyMode}>确认</Button>
                </FormItem>
                <FormItem>
                    <Button size="small" onClick={this.hideReplyModePopover}>取消</Button>
                </FormItem>
            </Form>);

        const formItemLayout = {
            labelCol: {
                span: 6
            },
            wrapperCol: {
                span: 14
            },
        };
        return (
            <div className="ReplyRuleItem">
                <div className="ReplyRuleItem-Header">
                    <h3>规则:{rule_name}</h3>
                    <Popover placement="bottomLeft"
                        content={content}
                        visible={this.state.titlePopVisible}
                        trigger="click">
                        <a className="btn-link" href="javascript:;" onClick={this.showTitleEditPopover}>编辑</a>
                    </Popover>
                    <a className="btn-link" href="javascript:;" onClick={this.showDeleteRuleModal}>删除</a>
                </div>
                <div className="ReplyRuleItem-Content">
                    <div className="ItemKeywordContent">
                        <p className="ItemKeywordTitle">关键词:</p>
                        <ul className="keyword_list_info">
                            {
                                keyword_list_info.length === 0
                                    ? <p className="noResult-tip">还没有任何关键字</p>
                                    :
                                    keyword_list_info.map((item, index) => {
                                        let { type, match_mode, content } = item;
                                        return (
                                            <li key={content + index}
                                                onClick={this.showKeywordEditModal.bind(this, index)}>
                                                <span className="text">{content}</span>
                                                <span className="key">{keywordTypes[match_mode]}</span>
                                                <a href="javascript:;" onClick={e => {
                                                    e.stopPropagation();
                                                    this.showDeleteKwModal(index)
                                                }}><i className="qmIcon close"></i></a>
                                            </li>
                                        );
                                    })
                            }
                        </ul>
                        <a className="btn-sm" onClick={this.showKeywordEditModal.bind(this, -1)}>添加关键词</a>
                    </div>
                    <div className="ItemReplyContent">
                        <p className="ItemAutoReply">自动回复: {replyModeTypes[reply_mode]}
                            <Popover placement="bottomLeft"
                                content={replyModeContent}
                                visible={this.state.replyModePopVisible}
                                trigger="click">
                                <a className="btn-link" href="javascript:;" onClick={this.showReplyModePopover}>编辑</a>
                            </Popover>
                        </p>
                        <ul className="reply_list_info">
                            {
                                reply_list_info.length === 0
                                    ? <p className="noResult-tip">还没有任何自动回复</p>
                                    :
                                    reply_list_info.map((item, index) => {
                                        let { type, content } = item;
                                        content = content || '';
                                        if (['page', 'goods', 'custom'].includes(content.split('__')[0])) {
                                            type = 'link';
                                        }
                                        return (
                                            <li key={content + index}>
                                                <span>【{mediaTypes[type]}】</span>
                                                {getReplyItem(item)}
                                                <a href="javascript:;"
                                                    onClick={this.showDeleteReplyModal.bind(this, index)}>删除</a>
                                                {
                                                    type == 'text'
                                                        ? <a href="javascript:;" onClick={this.showMediaModal.bind(this, index, item)}>编辑</a>
                                                        : null
                                                }
                                            </li>
                                        );
                                    })
                            }
                        </ul>
                        <a className="btn-sm" href="javascript:;"
                            onClick={this.showMediaModal.bind(this, -1, {})}>添加回复内容</a>
                    </div>
                </div>

                <Modal
                    visible={this.state.keywordModalVisible}
                    onOk={this.updateKeyword}
                    onCancel={this.hideKeywordEditModal}
                >
                    <Form >
                        <FormItem {...formItemLayout} label={<span>关键词&nbsp;</span>}>
                            <Input placeholder="关键词最多支持15个字" value={this.state.tempKwContent}
                                onChange={e => this.setState({ tempKwContent: e.target.value })} />
                        </FormItem>
                        <FormItem {...formItemLayout} label={<span>规则&nbsp;</span>}>
                            <RadioGroup onChange={e => (this.setState({ tempKwMatchMode: e.target.value }))}
                                value={this.state.tempKwMatchMode}>
                                <Radio value="equal">全匹配</Radio>
                                <Radio value="contain">模糊</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Form>
                </Modal>

                <Modal
                    wrapClassName="media-modal"
                    closable={false}
                    visible={mediaModalVisible}
                    onOk={() => {
                        if (tempReply.type && tempReply.content) {
                            this.updateReply()
                        } else {
                            message.warning(`请${tempReply.type == 'text' ? '输入' : '选择'}内容`);
                        }
                    }}
                    onCancel={() => this.setState({
                        mediaModalVisible: false,
                        tempReplyModalData: {
                            type: "text",
                            data: null,
                        },
                    })}>
                    <MassInput
                        textMaxLength={600}
                        data={tempReplyModalData}
                        onChange={({ type, data }) => {
                            // console.log({ type, data });
                            if (!data) return;

                            let content = "";
                            let extra = {};
                            if (type === "text") content = data;
                            if (type === "mpnews") {
                                content = data.media_id;
                                extra.title = data.content.news_item[0].title;
                            }
                            if (type === "news") {
                                content = data.id;
                                extra.title = data.articles[0].title;
                            }
                            if (type === "image") {
                                content = data.media_id;
                                extra.url = data.url;
                            }
                            if (type === "page") {
                                type = 'text';
                                content = data.type + '__' + data.data.url;
                                extra.url = data.type + '__' + data.data.url;
                            }
                            this.setState({
                                tempReply: { type, content, ...extra }
                            })
                        }} ref="massInput" />
                </Modal>
            </div>
        );
    }

    updateRule = (data) => {
        const { rule, changeItem } = this.props;
        const { ruleID } = rule;
        return changeItem({ ruleID, rule: { ...rule, ...data } });
    };

    deleteRule = () => {
        const { rule: { ruleID }, deleteItem } = this.props;
        deleteItem(ruleID);
    };

    showDeleteRuleModal = () => {
        const { rule: { rule_name } } = this.props;
        const _this = this;
        Modal.confirm({
            title: `是否确定删除规则: ${rule_name}?`,
            onOk() {
                _this.deleteRule()
            }
        });
    };
    showDeleteReplyModal = (index) => {
        const { rule: { reply_list_info } } = this.props;
        const _this = this;
        Modal.confirm({
            title: `是否确定删除回复内容?`,
            onOk() {
                _this.deleteReply(index)
            }
        });
    };
    deleteReply = (index) => {
        let { rule: { reply_list_info } } = this.props;
        let list = [...reply_list_info];
        list.splice(index, 1);
        this.updateRule({ reply_list_info: list }).then(() => {
            this.setState({ mediaModalVisible: false });
        });
    };
    updateReply = () => {
        let { tempReply, replyIndex } = this.state;
        let { rule: { reply_list_info } } = this.props;
        // console.log(tempReply);
        let list = reply_list_info;
        if (replyIndex < 0) {
            list.push(tempReply);
        } else {
            list[replyIndex] = tempReply;
        }
        // console.log("lis11111111t", {reply_list_info: list});
        // this.setState({mediaModalVisible: false});
        this.updateRule({ reply_list_info: list }).then(() => {
            this.refs.massInput.update({ type: "text", data: "" });
            this.setState({ mediaModalVisible: false });
        });
    };

    // 标题
    showTitleEditPopover = () => {
        this.setState({ titlePopVisible: true });
    };

    hideTitleEditPopover = () => {
        let _this = this;
        this.setState({ titlePopVisible: false }, () => {
            _this.setState({ title: _this.props.rule.rule_name })
        });
    };

    updateTitle = () => {
        if (!this.state.title || this.state.title.length > 30) {
            message.error("自定义规则名称不能为空或超过30字");
            return;
        }
        this.updateRule({ rule_name: this.state.title })
            .then(this.hideTitleEditPopover);
    };

    // 关键词
    showDeleteKwModal = (index) => {
        const { rule: { keyword_list_info } } = this.props;
        const _this = this;
        Modal.confirm({
            title: `是否确定删除关键词: ${keyword_list_info[index].content}?`,
            onOk() {
                _this.deleteKeyword(index)
            }
        });
    };

    deleteKeyword = (index) => {
        const { rule: { keyword_list_info } } = this.props;
        const list = [...keyword_list_info];
        list.splice(index, 1);
        this.updateRule({ keyword_list_info: list })
    };

    updateKeyword = () => {
        const { rule: { keyword_list_info } } = this.props;
        const { keywordIndex, tempKwContent, tempKwMatchMode, tempKwType } = this.state;

        if (!tempKwContent || tempKwContent.length > 15) {
            message.error("关键词不能空或者超过15个字");
            return;
        }
        if (!tempKwMatchMode) {
            message.error("请选择关键词匹配规则");
            return;
        }


        const list = [...keyword_list_info] || [];
        const index = keywordIndex < 0 ? list.length : keywordIndex;
        list[index] = {
            content: tempKwContent,
            match_mode: tempKwMatchMode,
            type: tempKwType
        };
        // console.log(list)
        this.updateRule({ keyword_list_info: list })
            .then(this.hideKeywordEditModal);
    };

    showKeywordEditModal = (index = -1) => {
        // console.log(index);
        const { rule: { keyword_list_info } } = this.props;
        const item = keyword_list_info[index] || { content: "", match_mode: "", type: "text" };
        this.setState({
            keywordModalVisible: true,
            keywordIndex: index,
            tempKwContent: item.content,
            tempKwMatchMode: item.match_mode,
            tempKwType: item.type
        });
    };

    hideKeywordEditModal = () => {
        this.setState({
            keywordModalVisible: false,
            keywordIndex: -1,
            tempKwContent: "",
            tempKwMatchMode: "",
            tempKwType: "text"
        })
    };

    // 回复模式
    showReplyModePopover = () => {
        const { rule: { reply_mode } } = this.props;
        this.setState({
            replyModePopVisible: true,
            tempReplyMode: reply_mode
        });
    };

    hideReplyModePopover = () => {
        this.setState({ replyModePopVisible: false });
    };

    updateReplyMode = () => {
        const { rule: { reply_mode } } = this.props;
        if (this.state.tempReplyMode === reply_mode) {
            this.hideReplyModePopover();
            return;
        }
        this.updateRule({ reply_mode: this.state.tempReplyMode })
            .then(this.hideReplyModePopover);
    };

    // 回复
    showReplyModeEditModal = (data) => {

    };

    showMediaModal = async (index, { type, content, url }) => {

        let data = null;

        if (type === "image") {

            data = { url, media_id: content };

        } else if (type === "mpnews") {

            const result = await this.props.getMPNewsDetail(content);

            data = { media_id: content, content: result };

        } else if (type === "text") {
            content = content || '';
            let array = content.split('__');
            if (['page', 'goods', 'custom'].includes(array[0])) {
                type = 'page';
                // console.log('page.url', array[1]);
                data = { type: array[0], data: { url: array[1] } };
            } else {
                data = content;
            }
        }

        this.setState({
            replyIndex: index,
            mediaModalVisible: true
        });

        if (index >= 0) {
            setTimeout(() => this.refs.massInput.update({ type, data }), 1);
        } else {
            setTimeout(() => this.refs.massInput.init(), 1);
        }
    }
}